package com.wn.framework.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import com.wn.framework.R
import com.wn.framework.ext.viewDataBind
import com.wn.framework.utils.LoadingUtils

/**
 * @Author: wn
 * @Date: 2024/9/14 15:53
 * @Description: 抽象的公用 BaseFragment
 * viewpager2 默认实现懒加载  onResume
 */
abstract class BaseFragment<T : ViewDataBinding> : Fragment {
  constructor() : super()

  // 次构造函数 传递 LayoutRes  取代 abstract获取 view
  constructor(@LayoutRes layout: Int) : super(layout)

  protected lateinit var mBinding: T

  // 首次加载数据
  private var isFirst = true

  // 弹窗 工具类
  private val dialogUtils: LoadingUtils by lazy {
    LoadingUtils(requireContext())
  }

  @LayoutRes
  protected abstract fun getLayoutRes(): Int

  /**
   * 初始化视图
   */
  protected open fun initView() {}

  /**
   * 初始化数据
   */
  protected open fun initData() {}

  /**
   * 懒加载数据
   */
  protected open fun initLazyData() {}

  /**
   * 初始化配置
   */
  protected open fun initConfig() {}

  override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?,
  ): View? {
    mBinding = viewDataBind(getLayoutRes(), container)
    return mBinding.root
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    // 将binding对象和view关联到一起
    mBinding.lifecycleOwner = viewLifecycleOwner
    initConfig()
    initData()
    initView()
  }

  /**
   * viewPager2 实现懒加载的 方式
   */
  override fun onResume() {
    super.onResume()
//    if (isFirst) {
    initLazyData()
//      isFirst = false
//    }
  }

  override fun onDestroyView() {
    super.onDestroyView()
    // 此处记得取消绑定，避免内存泄露
    if (::mBinding.isInitialized) {
      mBinding.unbind()
    }
    isFirst = true
  }

  /**
   * 加载中……弹框   不传值 默认加载中
   * @param str String
   */
  protected fun showLoading(str: String = getString(R.string.default_loading)) {
    dialogUtils.showLoading(str)
  }

  /**
   * 关闭提示框
   */
  protected fun dismissLoading() {
    dialogUtils.dismissLoading()
  }
}